package com.cnswhy.cloud.server.iot.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.MiniAppType;
import com.cnswhy.cloud.server.common.entity.mq.UserInfoTokenMsg;
import com.cnswhy.cloud.server.core.config.AlipayConfig;
import com.cnswhy.cloud.server.core.vo.RespVo;
import com.cnswhy.cloud.server.iot.config.CnswhyServerAppResourceServerConfigure;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j

@Api(tags = "支付宝小程序用户相关")
@Controller
@RequestMapping("/alipayUser")
public class AlipayUserController {
     @Autowired
    RedisService redisService;
    @Autowired
    MessageService messageService;
    @ApiOperation(value = "auth", httpMethod = "GET")
    @ApiParam(name = "code", value = "auth_code")
    @RequestMapping(value = "/auth", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public R<Object> auth(HttpServletRequest request, String code){
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL,AlipayConfig.APPID,AlipayConfig.RSA_PRIVATE_KEY,AlipayConfig.FORMAT,AlipayConfig.CHARSET,AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest();
        alipaySystemOauthTokenRequest.setGrantType("authorization_code");
        alipaySystemOauthTokenRequest.setCode(code);
        AlipaySystemOauthTokenResponse response = null;
        try {
            response = alipayClient.execute(alipaySystemOauthTokenRequest);
            log.info(JSON.toJSONString(response));
            if(response.isSuccess()){
                /**
                 *     user_id：用户支付宝 ID。
                 *
                 *     access_token：访问令牌。通过该令牌调用需要授权类接口。
                 *
                 *     expires_in：访问令牌的有效时间，单位是秒。
                 *
                 *     refresh_token：刷新令牌。通过该令牌可以刷新 access_token。
                 *
                 *     re_expires_in：刷新令牌的有效时间，单位是秒。
                 */
            } else {
                return R.fail(response.getSubMsg());
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", response.getUserId());
            messageService.sendQueueByObject(AmqpExchange.ALIPAY_TOKEN_MESSAGE,
                    UserInfoTokenMsg.builder().accessToken(response.getAccessToken())
                            .miniAppType(MiniAppType.ALIPAY)
                            .expiresIn(response.getExpiresIn())
                            .ReExpiresIn(response.getReExpiresIn())
                            .refreshToken(response.getRefreshToken())
                            .userId(response.getUserId()).build());
            return R.success(jsonObject);

        } catch (AlipayApiException e) {
            return R.fail(e.getErrMsg());
        }catch (Exception e) {
            e.printStackTrace();
            return R.fail("支付宝auth失败");
        }
    }


    @ApiOperation(value = "微信用户手机号信息解密", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "openId"),
            @ApiImplicitParam(name = "encryptedData", value = "encryptedData"),
            @ApiImplicitParam(name = "ivStr", value = "ivStr")
    })
    @RequestMapping(value = "/getPhone", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public R<Object> getPhone(HttpServletRequest request, String openId,String encryptedData,String ivStr){
        log.info("微信用户手机号信息解密：{} {} {}", openId,encryptedData,ivStr);
        RespVo vo = new RespVo();
        try {
            if(StringUtils.isBlank(openId)){
                throw new BizException("微信Code不可为空");
            }
            if(StringUtils.isBlank(encryptedData)){
                throw new BizException("encryptedData不可为空");
            }
            if(StringUtils.isBlank(ivStr)){
                throw new BizException("ivStr不可为空");
            }
            WxMaJscode2SessionResult jscode2SessionResult = (WxMaJscode2SessionResult)redisService.get("sessionResult" + openId);
            if(jscode2SessionResult == null){
                throw new BizException("该openId未找到");
            }
            WxMaPhoneNumberInfo p =CnswhyServerAppResourceServerConfigure.getWxMaService().getUserService().getPhoneNoInfo(jscode2SessionResult.getSessionKey(),encryptedData,ivStr);

            return R.success(p);
        }  catch (BizException e) {
            return R.fail(e.getMessage());
        }/*  catch (WxErrorException e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getError().getErrorMsg());
        }*/catch (Exception e) {
            return R.fail("微信用户手机号信息解密 失败");

        }
    }


}
